<?php
require_once __DIR__ . '/../core/config.php'; // 引入配置文件和数据库连接
require_once __DIR__ . '/../extend/phpmail/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// 辅助函数 ：获取邮箱服务器信息
function get_mail_server_info() {
    $pdo = connect_db();
    $stmt = $pdo->query("SELECT * FROM star_mail WHERE uid = 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// 辅助函数：生成随机用户密钥
function generate_random_key($length = 16) {
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $key .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $key;
}

// 辅助函数：获取用户IP
function get_user_ip() {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

// 用户注册函数
function little_user_reg($admin_account, $account, $password, $username) {
    $pdo = connect_db();
    try {
        if (!ctype_digit($account) || strlen($account) < 6 || strlen($account) > 12) {
            return json_response(500, '账号必须是数字，且长度大于6位小于12位');
        }
        if (!preg_match('/^(?=.*[a-zA-Z])(?=.*\d).{6,12}$/', $password)) {
            return json_response(500, '密码必须是数字和字母的组合，且长度大于6位小于12位');
        }
        $stmt = $pdo->prepare("SELECT vip_time FROM star_user WHERE account = :admin_account");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $admin_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$admin_info) {
            return json_response(500, '后台账号不存在');
        }
        if ($admin_info['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(500, '后台账号会员已到期');
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        if ($stmt->fetchColumn()) {
            return json_response(500, '账号已注册');
        }
        $stmt = $pdo->prepare("SELECT vip_time, balance, avatar, title FROM star_little_user_set WHERE uid = :uid");
        $stmt->bindParam(':uid', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $settings = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$settings) {
            return json_response(500, '未找到对应的配置信息，请检查管理员账号是否正确');
        }
        $vip_time = date('Y-m-d H:i:s', strtotime("+$settings[vip_time] days"));
        $reg_time = date('Y-m-d H:i:s');
        $login_token = date('Y-m-d H:i:s');
        $user_ip = get_user_ip();
        $user_key = generate_random_key();
        $eemail = $account . '@qq.com';
        $stmt = $pdo->prepare("INSERT INTO star_little_user (
            admin_account, account, password, username, vip_time, reg_time, balance, introduce, avatar, title, user_key, login_token, user_ip, eemail
        ) VALUES (
            :admin_account, :account, :password, :username, :vip_time, :reg_time, :balance, :introduce, :avatar, :title, :user_key, :login_token, :user_ip, :eemail
        )");
        $admin_account_bind = $admin_account;
        $account_bind = $account;
        $password_bind = password_hash($password, PASSWORD_BCRYPT);
        $username_bind = $username;
        $vip_time_bind = $vip_time;
        $reg_time_bind = $reg_time;
        $balance_bind = $settings['balance'];
        $introduce_bind = '';
        $avatar_bind = $settings['avatar'];
        $title_bind = $settings['title'];
        $user_key_bind = $user_key;
        $login_token_bind = $login_token;
        $user_ip_bind = $user_ip;
        $eemail_bind = $eemail;
        $stmt->bindParam(':admin_account', $admin_account_bind, PDO::PARAM_STR);
        $stmt->bindParam(':account', $account_bind, PDO::PARAM_STR);
        $stmt->bindParam(':password', $password_bind, PDO::PARAM_STR);
        $stmt->bindParam(':username', $username_bind, PDO::PARAM_STR);
        $stmt->bindParam(':vip_time', $vip_time_bind, PDO::PARAM_STR);
        $stmt->bindParam(':reg_time', $reg_time_bind, PDO::PARAM_STR);
        $stmt->bindParam(':balance', $balance_bind, PDO::PARAM_STR);
        $stmt->bindParam(':introduce', $introduce_bind, PDO::PARAM_STR);
        $stmt->bindParam(':avatar', $avatar_bind, PDO::PARAM_STR);
        $stmt->bindParam(':title', $title_bind, PDO::PARAM_STR);
        $stmt->bindParam(':user_key', $user_key_bind, PDO::PARAM_STR);
        $stmt->bindParam(':login_token', $login_token_bind, PDO::PARAM_STR);
        $stmt->bindParam(':user_ip', $user_ip_bind, PDO::PARAM_STR);
        $stmt->bindParam(':eemail', $eemail_bind, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '注册成功');
    } catch (PDOException $e) {
        return json_response(500, '注册失败: ' . $e->getMessage());
    }
}

// 用户登录函数
function little_user_login($admin_account, $account, $password) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT vip_time FROM star_user WHERE account = :admin_account");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $admin_info = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$admin_info) {
            return json_response(500, '后台账号不存在');
        }
        if ($admin_info['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(500, '后台账号会员已到期');
        }
        $stmt = $pdo->prepare("
            SELECT * FROM star_little_user 
            WHERE (account = :account OR eemail = :account) AND admin_account = :admin_account
        ");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号或邮箱不存在');
        }
        if ($user['login_token'] > date('Y-m-d H:i:s')) {
            return json_response(500, '已登录');
        }
        if (!password_verify($password, $user['password'])) {
            return json_response(500, '密码错误');
        }
        $login_token = date('Y-m-d H:i:s', strtotime("+7 days"));
        $stmt = $pdo->prepare("UPDATE star_little_user SET login_token = :login_token WHERE uid = :uid");
        $stmt->bindParam(':login_token', $login_token, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $user['uid'], PDO::PARAM_INT);
        $stmt->execute();
        return json_response(200, '登录成功', [
            'user_id' => $user['uid'],
            'account' => $user['account'],
            'eemail' => $user['eemail'],
            'login_token' => $login_token
        ]);
    } catch (PDOException $e) {
        return json_response(500, '登录失败: ' . $e->getMessage());
    }
}

//子用户私聊函数
function user_chat($send_user, $receive_user, $content, $admin_account) {
    $pdo = connect_db();
    $redis = connect_redis();
    try {
        $stmt = $pdo->prepare("SELECT login_token, user_permissions, username FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $send_user, PDO::PARAM_STR);
        $stmt->execute();
        $send_user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$send_user_info) {
            return json_response(500, '发送者账号未注册');
        }
        $current_time = time();
        $token_time = strtotime($send_user_info['login_token']);
        if ($token_time < $current_time) {
            return json_response(500, '发送者账号未登录');
        }
        if ($send_user_info['user_permissions'] == 2) {
            return json_response(500, '发送者账号已被封禁');
        }
        $stmt = $pdo->prepare("SELECT email FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $receive_user, PDO::PARAM_STR);
        $stmt->execute();
        $receive_user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$receive_user_info) {
            return json_response(500, '接收者账号不存在');
        }
        $stmt = $pdo->prepare("SELECT account FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $admin_user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$admin_user_info) {
            return json_response(500, '后台账号异常');
        }
        $chat_time = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("INSERT INTO star_little_user_chat (send_user, receive_user, chat_time, chat_information) VALUES (:send_user, :receive_user, :chat_time, :chat_information)");
        $stmt->bindParam(':send_user', $send_user, PDO::PARAM_STR);
        $stmt->bindParam(':receive_user', $receive_user, PDO::PARAM_STR);
        $stmt->bindParam(':chat_time', $chat_time, PDO::PARAM_STR);
        $stmt->bindParam(':chat_information', $content, PDO::PARAM_STR);
        $stmt->execute();
        $email_info = get_mail_server_info();
        if (!$email_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $email = new PHPMailer(true);
        try {
            $email->isSMTP();
            $email->Host = $email_info['host'];
            $email->SMTPAuth = true;
            $email->Username = $email_info['username'];
            $email->Password = $email_info['password'];
            $email->SMTPSecure = $email_info['agreement'];
            $email->Port = $email_info['port'];
            $email->setFrom($email_info['mail_address'], $email_info['mail_user']);
            $email->addAddress($receive_user_info['email']);
            $email->isHTML(true);
            $email->Subject = '您有新的用户留言';
            $email->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Comic Sans MS', cursive, sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');    
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 36px;
            margin: 0;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 18px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            background-color: #FF6600;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 15px;
        }
        .button:hover {
            background-color: #FF8800;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>{$send_user_info['username']}的问候</h1>
        </div>
        <div class='content'>
            <h1>亲爱的小伙伴：</h1>
            <h2>您有新留言，请在下方查看!</h2>
            <h3>留言内容:<span class='highlight'>{$content}</span></h3>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理-<a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";
            $email->send();
            return json_response(200, '消息发送成功');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '消息保存失败: ' . $e->getMessage());
    }
}


function recharge($account, $key, $admin_account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT key_time, key_balance FROM star_little_key WHERE some_key = ?");
        $stmt->execute([$key]);
        $key_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$key_info) {
            return json_response(500, '充值密钥不存在');
        }
        $stmt = $pdo->prepare("SELECT vip_time, balance FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($key_info['key_time'] !== null) {
            $vip_time = new DateTime($user['vip_time'] ?? 'now'); // 确保 vip_time 不为 null
            $vip_time->modify("+{$key_info['key_time']} day");
            $stmt = $pdo->prepare("UPDATE star_little_user SET vip_time = ? WHERE account = ?");
            $stmt->execute([$vip_time->format('Y-m-d H:i:s'), $account]);
        } else {
            $new_balance = $user['balance'] + $key_info['key_balance'];
            $stmt = $pdo->prepare("UPDATE star_little_user SET balance = ? WHERE account = ?");
            $stmt->execute([$new_balance, $account]);
        }
        $stmt = $pdo->prepare("DELETE FROM star_little_key WHERE some_key = ?");
        $stmt->execute([$key]);
        return json_response(200, '充值成功');
    } catch (PDOException $e) {
        return json_response(500, '充值失败: ' . $e->getMessage());
    }
}

// 生成充值密钥函数
function key_create($account, $type, $quantity, $count) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT user_permissions, login_token FROM star_little_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_permissions'] == 2) {
            return json_response(500, '账号已被封禁且权限不足!');
        }
        $current_time = time();
        $token_time = strtotime($user['login_token']);
        if ($token_time < $current_time) {
            return json_response(500, '账号未登录');
        }
        if ($type !== 'time' && $type !== 'balance') {
            return json_response(500, '无效的类型');
        }
        for ($i = 0; $i < $count; $i++) {
            $some_key = generate_random1_key();
            if ($type === 'time') {
                $stmt = $pdo->prepare("INSERT INTO star_little_key (some_key, key_time, key_balance, admin_user) VALUES (?, ?, NULL, ?)");
                $stmt->execute([$some_key, $quantity, $account]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO star_little_key (some_key, key_time, key_balance, admin_user) VALUES (?, NULL, ?, ?)");
                $stmt->execute([$some_key, $quantity, $account]);
            }
        }
        return json_response(200, '充值密钥创建成功');
    } catch (PDOException $e) {
        return json_response(500, '创建充值密钥失败: ' . $e->getMessage());
    }
}

// 辅助函数：生成随机密钥
function generate_random1_key() {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $part1 = substr(str_shuffle($characters), 0, 4);
    $part2 = substr(str_shuffle($characters), 0, 4);
    $part3 = substr(str_shuffle($characters), 0, 4);
    return $part1 . '-' . $part2 . '-' . $part3;
}

//获取卡密列表
function key_list($type, $price, $quantity, $admin_user) {
    $pdo = connect_db();
    try {
        if ($type !== 'time' && $type !== 'balance') {
            return json_response(500, '无效的类型参数');
        }
        if (!is_numeric($price) || $price <= 0) {
            return json_response(500, '价格必须是正数');
        }
        if (!is_numeric($quantity) || $quantity <= 0) {
            return json_response(500, '数量必须是正整数');
        }
        $stmt = $pdo->prepare("SELECT mail FROM star_user WHERE account = :admin_user");
        $stmt->bindParam(':admin_user', $admin_user, PDO::PARAM_STR);
        $stmt->execute();
        $user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user_info) {
            return json_response(500, '账号不存在');
        }
        $query = "SELECT some_key FROM star_little_key WHERE admin_user = :admin_user AND key_balance = :price";
        if ($type === 'time') {
            $query = "SELECT some_key FROM star_little_key WHERE admin_user = :admin_user AND key_time = :price";
        }
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':admin_user', $admin_user, PDO::PARAM_STR);
        $stmt->bindParam(':price', $price, PDO::PARAM_STR);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $results = array_slice($results, 0, $quantity);
        if (empty($results)) {
            return json_response(500, '未找到符合条件的密钥');
        }
        $email_info = get_mail_server_info();
        if (!$email_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $email = new PHPMailer(true);
        try {
            $email->isSMTP();
            $email->Host = $email_info['host'];
            $email->SMTPAuth = true;
            $email->Username = $email_info['username'];
            $email->Password = $email_info['password'];
            $email->SMTPSecure = $email_info['agreement'];
            $email->Port = $email_info['port'];
            $email->setFrom($email_info['mail_address'], $email_info['mail_user']);
            $email->addAddress($user_info['mail']);
            $email->isHTML(true);
            $email->Subject = '您生成的密钥列表';
            $email->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Comic Sans MS', cursive, sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 36px;
            margin: 0;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 18px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            background-color: #FF6600;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 15px;
        }
        .button:hover {
            background-color: #FF8800;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>密钥列表</h1>
        </div>
        <div class='content'>
            <h1>亲爱的用户：</h1>
            <h2>以下是您请求的密钥列表：</h2>
            <h3>密钥列表：</h3>
            <ul>
                " . implode('', array_map(function($key) {
                    return "<li>{$key['some_key']}</li>";
                }, $results)) . "
            </ul>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理 - <a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";
            $email->send();
            return json_response(200, '密钥列表已发送到您的邮箱');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

//获取后台用户的子用户
function get_user_information($admin_account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT vip_time, user_token FROM star_user WHERE account = :admin_account");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $admin_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$admin_info) {
            return json_response(500, '后台账号不存在');
        }
        if ($admin_info['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(500, '后台账号会员已到期');
        }
        if ($admin_info['user_token'] < date('Y-m-d H:i:s')) {
            return json_response(500, '未登录');
        }
        $stmt = $pdo->prepare("
            SELECT account, username, introduce, title, avatar, reg_time, vip_time, user_key, balance, user_ip, email, user_permissions
            FROM star_little_user
            WHERE admin_account = :admin_account
        ");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (empty($users)) {
            return json_response(500, '未找到相关用户信息');
        }
        return json_response(200, '获取成功', $users);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}

//获取子用户数量
function get_little_user_number($admin_account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT vip_time, user_token FROM star_user WHERE account = :admin_account");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $admin_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$admin_info) {
            return json_response(500, '后台账号不存在');
        }
        if ($admin_info['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(500, '后台账号会员已到期');
        }
        if ($admin_info['user_token'] < date('Y-m-d H:i:s')) {
            return json_response(500, '未登录');
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) as user_count FROM star_little_user WHERE admin_account = :admin_account");
        $stmt->bindParam(':admin_account', $admin_account, PDO::PARAM_STR);
        $stmt->execute();
        $user_count = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user_count) {
            return json_response(500, '未找到相关用户信息');
        }
        return json_response(200, $user_count);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}